// sslUrl.js

var AUTH_SUB_REQUEST_URL = "/accounts/AuthSubRequest";

function setUpWindow() {
  updateSingleUseToken(document.URL);
  setAuthSubIframeSrc();
  showHideDivs();
  registerEventHandlers();
}

function showHideDivs() {
  var httpMethodSelect = document.getElementById("method");
  for (var i = 0; i < httpMethodSelect.options.length; i++) {
    var httpMethodOption = httpMethodSelect.options[i];
    var div = document.getElementById(httpMethodOption.value);
    div.style.display = httpMethodOption.selected ? "block" : "none";
  }
}


function trim(string) {
  return string.replace(/^\s+|\s+$/g, "");
}

function getAuthSubUrl(documentUrl) {
  var nextUrl = documentUrl.split("?")[0];
  var scopeUrl = getAuthSubScope(documentUrl);
  return AUTH_SUB_REQUEST_URL +
      "?next=" + encodeURIComponent(nextUrl) +
      "&scope=" + encodeURIComponent(scopeUrl) +
      "&session=1";
}

function getAuthSubScope(documentUrl) {
  var scopeUrlEndIndex = documentUrl.length + 1;
  var indexOfDoubleSlash = documentUrl.indexOf("//");
  var indexOfSlashAfterDomain =
    documentUrl.indexOf("/", indexOfDoubleSlash + 2);
  if (indexOfSlashAfterDomain > -1) {
    scopeUrlEndIndex = indexOfSlashAfterDomain;
  }
  return documentUrl.substring(0, scopeUrlEndIndex) + "/base";
}

function registerEventHandlers() {
  registerOnClickHandler("postButton", postButtonOnClickHandler);
  registerOnClickHandler("putButton", putButtonOnClickHandler);
  registerOnClickHandler("deleteButton", deleteButtonOnClickHandler);
  registerOnClickHandler("queryButton", queryButtonOnClickHandler);
  registerOnClickHandler("batchButton", batchButtonOnClickHandler);
  registerOnChangeHandler("method", showHideDivs);
}

function postButtonOnClickHandler() {
  publishButtonOnClickHandler("POST");
}

function putButtonOnClickHandler() {
  publishButtonOnClickHandler("PUT");
}

function deleteButtonOnClickHandler() {
  publishButtonOnClickHandler("DELETE");
}

function publishButtonOnClickHandler(requestMethod) {
  requestButtonOnClickHandler(requestMethod, requestMethod, "/base/feeds");
}

function queryButtonOnClickHandler() {
  requestButtonOnClickHandler("GET", "GET", "/base/feeds");
}

function batchButtonOnClickHandler() {
  requestButtonOnClickHandler("POST", "BATCH", "/base/feeds")
}

function requestButtonOnClickHandler(requestMethod,
                                     displayElementIdPrefix,
                                     urlPrefix) {
  var requester = new Requester();
  var responder = new Responder(displayElementIdPrefix);
  var body = document.getElementById(displayElementIdPrefix + "body");
  var bodyValue = body ? body.value : null;
  var urlSuffixElement = document.getElementById(displayElementIdPrefix + "urlSuffix");
  var urlSuffix = urlSuffixElement ? "/" + urlSuffixElement.value : "";
  var url = urlPrefix + urlSuffix;
  requester.request(requestMethod, url, bodyValue, responder,
      displayElementIdPrefix);
}
